<?php

namespace app\core;

class Response extends \think\Response
{
    /**
     * 系统错误码
     * @var int[]
     */
    private $error_codes = [
        "OK" => 0, // 成功状态
        "SYSTEM" => 400, // 系统错误
        "PERMISSION" => 403, // 权限错误
        "INVALID" => 401, // 登录失效
        "UNKNOW" => 409, // 未知错误
        "VALIDATE" => 405, // 参数错误
        "BUSINESS" => 406, // 业务错误
        "PARSMETER" => 407, // 参数必填未传
    ];

    /**
     * 业务错误码
     * @var int[]
     */
    private $business_error_codes = [
        'TEST' => 10001,
    ];

    /**
     * @param array $args
     * @param bool $newInstance
     * @return Response
     */
    public static function invoke(array $args = [], bool $newInstance = false): Response
    {
        return app(self::class, $args, $newInstance);
    }

    /**
     * 系统错误
     * @return void
     */
    public function systemError(string $msg = '系统错误')
    {
        $this->error($msg, "SYSTEM");
    }

    /**
     * 权限错误
     * @return void
     */
    public function permissionError()
    {
        $this->error("暂无权限", "PERMISSION");
    }

    /**
     * 登录失效
     * @return void
     */
    public function invalidError()
    {
        $this->error("登录失效", "INVALID");
    }

    /**
     * 未知错误
     * @return void
     */
    public function unknowError()
    {
        $this->error("未知错误", "UNKNOW");
    }

    /**
     * 参数错误
     * @param string $msg
     * @return void
     */
    public function validateError(string $msg = '参数错误')
    {
        $this->error($msg, "VALIDATE");
    }

    /**
     * 成功响应
     * @param null $data
     * @param string $msg
     * @param string $code
     */
    public function success($data = null, string $msg = "操作成功", string $code = 'OK'): void
    {
        $this->json([
            "code" => $this->getErrorCode($code),
            "msg" => $msg,
            "data" => $data,
        ]);
    }


    /**
     * 错误响应
     * @param string $msg
     * @param string $code
     */
    public function error(string $msg = "系统错误", string $code = 'SYSTEM_ERROR'): void
    {
        $this->json([
            "code" => $this->getErrorCode($code),
            "msg" => $msg,
            "data" => null,
        ]);
    }

    /**
     * 响应输出
     * @param $res
     * @param int $code
     */
    public function json($res, int $code = 200)
    {
        self::create($res, 'json', $code)->send();
        exit(0);
    }

    /**
     * @param $key
     * @return int
     */
    public function getErrorCode($key): int
    {
        $codes = array_merge($this->error_codes, $this->business_error_codes);
        return $codes[$key] ?? $codes['UNKNOW'];
    }
}